package org.dromara.common.core.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.model.PutObjectResult;
import org.dromara.common.core.utils.file.FileUploadUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

public class OssUtil {

    // endpoint以杭州为例，其它region请按实际情况填写。simple-mall.oss-cn-beijing.aliyuncs.com
    private static final String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private static final String accessKeyId = "LTAI5tFMChM8vZoNHi1kX5xs";
    private static final String accessKeySecret = "j9SK49ar6pqAUyW9PegrMDTYtXqIWt";
    private static final String bucketName = "yuedou";

    private static final int validity = 60 * 1000;


    public static void main(String[] args){
        String url = "/article/1/2c1157af-7612-43bd-b34c-e928338ab6a9.png";
        url = url.substring(1);
        boolean bl = deleteObjByKey(url);
        if(bl){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
    }

    /**
     * 上传文件
     * @param inputStream 要上传的文件流
     * @param fileName 要上传的文件名字
     * @param upload_type 要上传的文件类型
     */
    public static boolean upload(InputStream inputStream,String fileName,int upload_type) {
        boolean ret = false;
        // 上传文件流
        if (inputStream!=null){
			OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //inputStream = new FileInputStream("/Users/ran/Desktop/会议记录0521.txt");
            String prefix = FileUploadUtils.getUploadPrefix(upload_type);
			System.out.println("文件路径：" + prefix + fileName);
            if (prefix!=null){
				try{
					PutObjectResult putObjectResult = ossClient.putObject(bucketName, prefix + fileName, inputStream);
					String eTag = putObjectResult.getETag();
					System.out.println("upload " + prefix + fileName +"-->"+ eTag);

				} catch (OSSException oe) {
					System.out.println("Caught an OSSException, which means your request made it to OSS, "
						+ "but was rejected with an error response for some reason.");
					System.out.println("Error Message:" + oe.getErrorMessage());
					System.out.println("Error Code:" + oe.getErrorCode());
					System.out.println("Request ID:" + oe.getRequestId());
					System.out.println("Host ID:" + oe.getHostId());
				} catch (ClientException ce) {
					System.out.println("Caught an ClientException, which means the client encountered "
						+ "a serious internal problem while trying to communicate with OSS, "
						+ "such as not being able to access the network.");
					System.out.println("Error Message:" + ce.getMessage());
				}
            }
            // 关闭client。
            ossClient.shutdown();
			System.out.println("upload "+ prefix + fileName +"是否成功-->"+ (ret?"YES":"NO"));
        }
        return ret;
    }

    /**
     * 上传文件
     * @param inputStream 要上传的文件流
     * @param fileName 要上传的文件名字
     */
    public static boolean upload(InputStream inputStream,String fileName) {
        boolean ret = false;
        // 上传文件流
        if (inputStream!=null){
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //inputStream = new FileInputStream("/Users/ran/Desktop/会议记录0521.txt");
//            String prefix = getUploadPrefix(upload_type);
            if (fileName!=null){
                PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, inputStream);
                String eTag = putObjectResult.getETag();
                System.out.println("upload "+fileName +"-->"+ eTag);
            }
            // 关闭client。
            ossClient.shutdown();
        }
        System.out.println("upload "+fileName +"是否成功-->"+ (ret?"YES":"NO"));
        return ret;
    }

    /**
     * 根据key获取url
     * @param object_key
     * @return
     */
    public static String getSignUrl(String object_key){
        //创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
        //validity url的有效期
        URL url = ossClient.generatePresignedUrl(bucketName, object_key, new Date(new Date().getTime()+validity));
		//关闭client
        ossClient.shutdown();
        return url==null?null:url.toString();
    }


    /**
     * 删除文件
     * @param objKey
     * @return
     */
    public static boolean deleteObjByKey(String objKey) {
        boolean ret = false;
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        ossClient.deleteObject(bucketName,objKey);
        // Object是否存在。
        ret = ossClient.doesObjectExist(bucketName, objKey);
        ossClient.shutdown();
        return !ret;
    }

    public static BufferedImage getImageInfoByUrl(String urlStr){

        try{
            URL url = new URL(urlStr);
            URLConnection urlConnection = url.openConnection();
            int length = urlConnection.getContentLength();
            System.out.print("length: " + length);
            if(length == -1){
                System.out.print("image not exist");
            }else{
                BufferedImage sourceImg = ImageIO.read(url);
                System.out.print("image width:" + sourceImg.getWidth());
                System.out.print("image height:" + sourceImg.getHeight());
                return sourceImg;
            }
        }catch (MalformedURLException e){
//            logger.info("url not right " + e.getMessage(), e);
        } catch (IOException e){
//            logger.info("IOException " + e.getMessage(), e);
        }
        return null;
    }
}
